<?php
namespace Components\Account\User\Order;

class Logic {
	private function getPaginate($builder, $limit, $page) {
		return ['code' => 0, 'pager'=>(new \Phalcon\Paginator\Adapter\QueryBuilder([
			'builder' => $builder,
			'limit' => $limit,
			'page' => $page
		])) -> getPaginate()];
	}

	private function makeBuilder($parameters) {
		$builder = new \Phalcon\Mvc\Model\Query\Builder();
		$builder -> from(__NAMESPACE__ . '\\Model')
		-> orderBy('status ASC,user_order_id DESC');

		if(isset($parameters['conditions'])) {
			$builder -> andWhere($parameters['conditions']);
		}

		return $builder;
	}

	public function pager($parameters = [], $limit = 10, $page = 1) {
		$result = $this -> getPaginate($this -> makeBuilder($parameters), $limit, $page);
		if($result['code'] != 0) {return $result;}
		$pager = [];
		foreach($result['pager'] -> items as $k => $item) {
			$pager['items'][$k] = $item -> toArray();
			$pager['items'][$k]['user'] = \Components\Account\User\Model::findFirst(['conditions'=>'user_id = ' . $item -> user_id,'columns'=>'account']) -> toArray();
			$pager['items'][$k]['user_address'] = \Components\Account\User\Address\Model::findFirst('address_id = ' . $item -> user_address_id) -> toArray();
			$pager['items'][$k]['user_order_products'] = Products\Model::find('user_order_id = ' . $item -> user_order_id) -> toArray();
		}
		$pager['first'] = $result['pager'] -> first;
		$pager['before'] = $result['pager'] -> before;
		$pager['current'] = $result['pager'] -> current;
		$pager['last'] = $result['pager'] -> last;
		$pager['next'] = $result['pager'] -> next;
		$pager['total_pages'] = $result['pager'] -> total_pages;
		$pager['total_items'] = $result['pager'] -> total_items;
		$pager['limit'] = $result['pager'] -> limit;

		return ['code'=>0,'pager'=>$pager];
	}

	public function match($parameters = [], $limit = 10, $page = 1) {
		$builder = $this -> makeBuilder() -> andWhere('tb.status = 0 AND tb.amount <= ' . $parameters['trade_sell'] -> amount . ' AND tb.from_user_id != ' . $parameters['trade_sell'] -> from_user_id);

		return $this -> getPaginate($builder, $limit, $page);
	}
}
